package com.graduation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.common.domain.dto.PageDTO;
import com.graduation.common.exceptions.BizException;
import com.graduation.mapper.TagMapper;
import com.graduation.pojo.po.Tag;
import com.graduation.pojo.query.TagQuery;
import com.graduation.pojo.vo.TagVO;
import com.graduation.service.TagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Override
    public PageDTO<TagVO> pageTags(TagQuery query) {
        // 构建查询条件
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getName()), Tag::getName, query.getName())
                .orderByDesc(Tag::getUsageCount)
                .orderByDesc(Tag::getCreateTime);

        // 分页查询
        Page<Tag> page = page(query.toMpPageByCreateTime(), wrapper);
        
        // 转换为VO并返回PageDTO
        List<TagVO> voList = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageDTO.of(page.getPages(), page.getTotal(), voList);
    }

    @Override
    public TagVO getTagById(Long id) {
        Tag tag = getById(id);
        if (tag == null) {
            throw new BizException("标签不存在");
        }
        return convertToVO(tag);
    }

    @Override
    public void saveTag(Tag tag) {
        // 检查标签名称是否已存在
        boolean exists = lambdaQuery()
                .eq(Tag::getName, tag.getName())
                .exists();
        if (exists) {
            throw new BizException("标签名称已存在");
        }

        // 初始化使用次数
        if (tag.getUsageCount() == null) {
            tag.setUsageCount(0);
        }
        
        save(tag);
    }

    @Override
    public void updateTag(Tag tag) {
        Tag existTag = getById(tag.getId());
        if (existTag == null) {
            throw new BizException("标签不存在");
        }

        // 检查标签名称是否被其他标签使用
        if (StrUtil.isNotBlank(tag.getName()) && 
            !tag.getName().equals(existTag.getName())) {
            boolean exists = lambdaQuery()
                    .eq(Tag::getName, tag.getName())
                    .ne(Tag::getId, tag.getId())
                    .exists();
            if (exists) {
                throw new BizException("标签名称已存在");
            }
        }
        
        updateById(tag);
    }

    @Override
    public void deleteTag(Long id) {
        Tag tag = getById(id);
        if (tag == null) {
            throw new BizException("标签不存在");
        }

        // TODO: 检查是否有关联的文档
        // boolean hasDocuments = documentTagService.lambdaQuery()
        //         .eq(DocumentTag::getTagId, id)
        //         .exists();
        // if (hasDocuments) {
        //     throw new BizException("该标签下存在关联文档，无法删除");
        // }

        removeById(id);
    }

    /**
     * 转换为VO对象
     */
    private TagVO convertToVO(Tag tag) {
        TagVO vo = new TagVO();
        BeanUtil.copyProperties(tag, vo);
        return vo;
    }
}
